package com.zw.pdm.module.designtask.service;

import com.zw.pdm.entity.basic.Dept;
import com.zw.pdm.entity.com.ComTaskName;
import com.zw.pdm.entity.com.DsnProCommon;
import com.zw.pdm.entity.com.DsnTaskCommon;
import com.zw.pdm.entity.designtask.DsnProStruct;
import com.zw.pdm.module.designtask.mapper.DesignTaskMapper;
import com.zw.pdm.module.designtask.mapper.ProStructMapper;
import com.zw.pdm.module.designtask.repository.DsnProCommonRepository;
import com.zw.pdm.module.designtask.repository.DsnProStructRepository;
import com.zw.pdm.module.designtask.repository.DsnTaskCommonRepository;
import com.zw.pdm.module.report.model.Project;
import com.zw.pdm.module.system.mapper.UserMapper;
import com.zw.pdm.module.system.repository.DeptRepository;
import com.zw.pdm.module.system.service.LogService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * @Description:
 * @Author: China.wsg
 * @Date: 2020/10/13 14:12
 */
@Service
@SuppressWarnings("all")
public class DesignTaskAddService {

    @Autowired
    private DesignTaskMapper designTaskMapper;
    @Autowired
    private LogService logService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DsnTaskCommonRepository taskRepository;
    @Autowired
    private DsnProCommonRepository comProStatusRepository;
    @Autowired
    private DeptRepository deptRepository;
    @Autowired
    private ProStructService proStructService;
    @Autowired
    private DsnProStructRepository dsnProStructRepository;
    @Autowired
    private ProStructMapper proStructMapper;
    @Autowired
    private DsnProcessService dsnProcessService;

    /**
     * 按项目编号查询项目信息
     */
    public List<Project> findProjectsByQuery(Project project) {
        return designTaskMapper.findProjectsByQuery(project);
    }

    /**
     * 根据 所 查询
     */
    public List<Dept> findDeptByPid(Integer pid) {
        return designTaskMapper.findDeptByPid(pid);
    }

    /**
     * 下达任务单
     *
     * @param projectId 项目ID
     * @param sectionId 科室ID
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean distribute(Integer projectId, Integer[] sectionId) {
        Project project = designTaskMapper.findProjectById(projectId);

        // 已经分配不允许再次分配，数据存在说明已经被分配
        List<DsnProCommon> comProStatuses = comProStatusRepository.findByProIdAndStatusTypeNameAndStatus(projectId, "设计任务下达状态", 2);
        if (comProStatuses.size() > 0) {
            return false;
        }

        // 保存操作日志
        logService.saveLog("下达设计任务", "项目名：" + project.getName() + "<br>项目号：" + project.getCode());

        // 生成设计科室任务
        DsnTaskCommon comTask;
        StringBuilder designDepts = new StringBuilder();
        for (Integer id : sectionId) {
            if (id != null) {
                Dept dept = deptRepository.getOne(id);
                designDepts.append(dept.getName() + ",");

                // 取得设计所有任务类型
                List<ComTaskName> taskNames = designTaskMapper.findTaskNameByDict("'设计科室任务'");
                for (ComTaskName taskName : taskNames) {
                    comTask = new DsnTaskCommon();
                    comTask.setDeptId(id);
                    comTask.setProId(projectId);
                    comTask.setProCode(project.getCode());
                    comTask.setProName(project.getName());
                    comTask.setComTaskNameId(taskName.getId());
                    comTask.setComTaskName(taskName.getName());

                    String sepcial = dsnProcessService.findDeptInfoByAccount(id);
                    Integer specialId = 0;
                    if (sepcial.equals("机械")) {
                        specialId = 60;
                    } else if (sepcial.equals("流体")) {
                        specialId = 61;
                    } else if (sepcial.equals("自动化")) {
                        specialId = 62;
                    }
                    comTask.setSpecialId(specialId);
                    comTask.setSpecial(sepcial);
                    taskRepository.save(comTask);
                }
            }
        }

        // 生成设计项目任务
        List<ComTaskName> taskNames = designTaskMapper.findTaskNameByDict("'设计项目任务'");
        for (ComTaskName taskName : taskNames) {
            comTask = new DsnTaskCommon();
            comTask.setProId(projectId);
            comTask.setProCode(project.getCode());
            comTask.setProName(project.getName());
            comTask.setComTaskNameId(taskName.getId());
            comTask.setComTaskName(taskName.getName());
            taskRepository.save(comTask);
        }

        // 更新项目信息
        DsnProCommon comProStatus = new DsnProCommon();
        comProStatus.setProId(projectId);
        comProStatus.setProCode(project.getCode());
        comProStatus.setStatusTypeId(1);
        comProStatus.setStatusTypeName("设计任务下达状态");
        comProStatus.setStatus(2);
        comProStatus.setDepts(designDepts.toString().substring(0, designDepts.lastIndexOf(",")));
        comProStatusRepository.save(comProStatus);

        return true;
    }

    /**
     * 根据部门名称查询部门ID
     *
     * @param sectionName
     * @return
     */
    public Integer[] transformId(String[] sectionName) {

        // 数组转集合
        List<String> sectionNameList = Arrays.asList(sectionName);

        // 取得项目ID集合
        StringBuilder sb;
        sb = new StringBuilder();
        for (int i = 0; i < sectionNameList.size(); i++) {
            sb.append(sectionNameList.get(i)).append(",");
        }
        String sectionNameQuery = "'" + StringUtils.join(sb.toString().substring(0, sb.toString().length() - 1).split(","), "','") + "'";
        List<Integer> list = designTaskMapper.findDeptIdByDeptNames(sectionNameQuery);

        // 集合转数组
        Integer[] sectionId = new Integer[list.size()];
        list.toArray(sectionId);
        return sectionId;
    }

    /**
     * 项目看板生产下达添加产品结构
     */
    public boolean produceDistribute(Integer projectId,String proCode,String proName) {
        return designTaskMapper.insertProduceStruct(projectId,proCode,proName) > 0;
    }

    /**
     * 项目类型变更接口
     *
     * @param projectId      项目主键
     * @param changeType     0只调科室 1变更成设计 2变更成生产
     * @param befSectionName 调整前科室
     * @param aftSectionName 调整后科室
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean taskChangeInterface(Integer projectId, Integer changeType, String[] befSectionName, String[] aftSectionName) {
        if (changeType == 0) {
            // 该方法尚未开发 bug 20201109

        } else if (changeType == 1) {
            // 删除原生产产品结构（机械、流体、自动化）整体
            delProStruByProId(projectId);
            // 重新任务分配和创建产品结构
            Integer[] sectionId = transformId(aftSectionName);
            distribute(projectId, sectionId);
        } else if (changeType == 2) {
            // 删除科室任务信息表（设计院和工艺可通用）
            designTaskMapper.delTaskCommonByProId(projectId);
            // 删除项目下达记录表
            designTaskMapper.delTaskCommonByProId(projectId);
            // 添加产品结构整体（机械、流体、自动化）
            designTaskMapper.insertProduceStruct(projectId,"","");
        }
        return true;
    }

    /**
     * 删除产品结构
     *
     * @param proId 项目ID
     * @return
     */
    public boolean delProStruByProId(Integer proId) {

        List<DsnProStruct> dsnProStructs = dsnProStructRepository.findByProIdAndIsDelOrderBySpecialIdAscCreateCodeAscIdAsc(proId, 0);
        for (int i = 0; i < dsnProStructs.size(); i++) {
            // 判断是否存在提报计划
            if (proStructService.existRepSheet(dsnProStructs.get(i))) {
                return false;
            }
            // 判断是否存在制作件计划
            if (proStructService.existMakeSheet(dsnProStructs.get(i))) {
                return false;
            }
        }
        proStructMapper.delProStruByProId(proId);
        return true;
    }

}
